//
//  AboutusController.m
//  Contacts
//
//  Created by beisheng03 on 2017/10/25.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "MyWebViewController.h"
#import <WebKit/WebKit.h>
#import "WKDelegetaController.h"

@interface MyWebViewController ()<WKNavigationDelegate,WKScriptMessageHandler,
WKDelegateControllerDelegate>


@property (nonatomic, weak) WKWebView *webView;

@property (nonatomic, strong) WKUserContentController  *userContentController;

@property (nonatomic, weak) UIProgressView *prosess;

@end

@implementation MyWebViewController


- (UIProgressView *)prosess{
    if (!_prosess) {
        UIProgressView *pro = [[UIProgressView alloc]init];
        _prosess = pro;
        _prosess.progressTintColor = darkGray;
        
        [self.view addSubview:pro];
    }
    
    
    return _prosess;
}


- (WKWebView *)webView{
    if (!_webView) {
        //配置环境
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        
        _userContentController = [[WKUserContentController alloc]init];
        
        config.userContentController = _userContentController;
        
        
        WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];
        
        //注册方法
        
        WKDelegetaController *delegateController = [[WKDelegetaController alloc]init];
        
        delegateController.delegate = self;
        
        
        [_userContentController addScriptMessageHandler:delegateController name:@"sendMessage"];//注册一个name为sendMessage的js方法
        
        
        
        
        _webView = webView;
        [self.view addSubview:webView];
        
    }
    
    return _webView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.webView.navigationDelegate = self;
    
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    
//    self.navigationItem.title = @"新城百态";
    
    if (@available(iOS 11.0, *)) {
        

        
//        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
        
        
        self.navigationItem.largeTitleDisplayMode =  UINavigationItemLargeTitleDisplayModeNever;
        
//        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;


        if (IPhoneX) {
            _webView.scrollView.contentInset = UIEdgeInsetsMake(88, 0, 0, 0);

        } else {
            _webView.scrollView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);

        }
        
//        _webView.scrollView.scrollIndicatorInsets = _webView.scrollView.contentInset;
        
    }
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    
    
    
    
    
    self.prosess.frame = CGRectMake(0, 64, KScreenW, 5);
    
    if (IPhoneX) {
        
        self.prosess.frame = CGRectMake(0, 88, KScreenW, 5);
        
    }
    
    // Do any additional setup after loading the view.
}


#pragma mark - WKScriptMessageHandler  JS调用OC

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    NSLog(@"%f",self.webView.estimatedProgress);
    
    self.prosess.progress = self.webView.estimatedProgress;
    
    if (self.prosess.progress == 1) {
        self.prosess.hidden = YES;
    }
    
    self.navigationItem.title = self.webView.title;
    
    
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    //    NSInteger type = [message.body integerValue];
    //
    //    if (type == 2) {
    //        [self.navigationController popViewControllerAnimated:YES];
    //    }
    //
    //
    //    if (type == 3) {
    //        [self.navigationController popViewControllerAnimated:YES];
    //    }
    
    
}


#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
    
    
    
    
    
}


//内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
    
    
    
    
    
}



//OC调JS方法
//页面加载完成后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    [SVProgressHUD dismiss];
    
    //    NSLog(@"%@",[NSString stringWithFormat:@"get_ios_key('%@')",[UserViewModel shareUserViewModel].access_token]);@"get_ios_key('8888888888')"
    //say()是JS方法名，completionHandler是异步回调block
    [webView evaluateJavaScript:@"DFSFSD" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        
        //        NSLog(@"%@",result);
        
        
        
        
        
        //        NSLog(@"%@",[NSThread currentThread]);
    }];
    
}


//页面加载失败后调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
    
    
}


//收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    
    if ([navigationResponse.response.URL.absoluteString isEqualToString:@"http://xiaojingsc.test.beisheng.wang/wap/tmpl/cart_list.html"]) {
        decisionHandler(WKNavigationResponsePolicyCancel);
        
        
        
        
    } else {
        decisionHandler(WKNavigationResponsePolicyAllow);
    }
    
    //允许跳转
    
    
    //还允许跳转
    //
    
    
    
}



//发送请求前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    //    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    
    //还允许跳转
    //    decisionHandler(WKNavigationActionPolicyCancel);
    
    
    
    
}


- (void)dealloc{
    //前面加过的方法一定要remove掉
    [_userContentController removeScriptMessageHandlerForName:@"sendMessage"];
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
    [self.webView removeObserver:self forKeyPath:@"title"];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

